package com.example.voiceassistant.asr;

import com.example.voiceassistant.ai.AIResponseService;
import com.example.voiceassistant.config.ConfigManager;
import com.example.voiceassistant.monitoring.MonitoringService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.Duration;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import okhttp3.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Base64;
import java.util.Map;
import java.io.IOException;

/**
 * 流式语音识别的演示实现。
 */
public class AsrStreamingEngine {

    private static final Logger LOGGER = LoggerFactory.getLogger(AsrStreamingEngine.class);

    private final MonitoringService monitoringService;
    private final AIResponseService aiResponseService;
    private final ExecutorService executorService = Executors.newSingleThreadExecutor();
    private final Duration debounceDuration = Duration.ofMillis(800);

    private volatile long lastFrameTimestamp = -1;
    private final StringBuilder buffer = new StringBuilder();

    private final Locale locale;
    private final OkHttpClient httpClient = new OkHttpClient();
    private final ObjectMapper objectMapper = new ObjectMapper();
    private final ConfigManager configManager;

    public AsrStreamingEngine(ConfigManager configManager, MonitoringService monitoringService, AIResponseService aiResponseService) {
        this.configManager = configManager;
        this.monitoringService = monitoringService;
        this.aiResponseService = aiResponseService;
        this.locale = Locale.forLanguageTag(configManager.getLocale());
    }

    public void processAudioData(byte[] wavData, RecognitionCallback callback) { // 改为 byte[]
        System.out.println("ASR processing audio data, length: " + wavData.length); // Debug
        monitoringService.counter("asr.audio.accepted").increment();

        executorService.submit(() -> {
            try {
                String base64Audio = Base64.getEncoder().encodeToString(wavData);
                // 构建请求体
                String json = "{ \"model_id\": \"" + configManager.getAsrModel() + "\", \"audio\": \"" + base64Audio + "\", \"language\": \"zh\" }";
                RequestBody body = RequestBody.create(json, MediaType.get("application/json"));
                Request request = new Request.Builder()
                        .url(configManager.getAsrEndpoint())
                        .addHeader("Authorization", "Bearer " + configManager.getAsrApiKey())
                        .post(body)
                        .build();

                Response response = httpClient.newCall(request).execute();
                if (response.isSuccessful()) {
                    String respBody = response.body().string();
                    System.out.println("ASR API response: " + respBody); // Debug
                    // 解析 JSON，假设返回 { "text": "识别文字" }
                    Map<String, Object> result = objectMapper.readValue(respBody, Map.class);
                    String text = (String) ((Map) result.get("data")).get("text"); // 调整根据实际 API 格式
                    if (text == null || text.trim().isEmpty()) {
                        text = "未识别到清晰语音"; // Fallback
                    }
                    monitoringService.counter("asr.recognition.completed").increment();
                    LOGGER.info("ASR 识别文本: {}", text);
                    System.out.println("ASR recognized text: " + text);
                    callback.onRecognized(text, aiResponseService.generateReply(text, locale));
                } else {
                    throw new IOException("API error: " + response.code());
                }
            } catch (Exception e) {
                monitoringService.counter("asr.error").increment();
                LOGGER.error("ASR API 调用失败", e);
                System.out.println("ASR fallback: 用户语音输入 (API error)"); // 模拟 fallback
                callback.onRecognized("用户语音输入", aiResponseService.generateReply("用户语音输入", locale));
                callback.onError(e);
            }
        });
    }

    public void shutdown() {
        httpClient.dispatcher().executorService().shutdown();
        executorService.shutdownNow();
    }

    public interface RecognitionCallback {
        void onRecognized(String text, String aiReply);
        void onError(Throwable throwable);
    }
}

